const _ = require("lodash");
const moment = require("moment");

const models = require(__base + '/models');
const errcode = require(__util + "/errcode");
const ct = require(__util + "/catch"); // 路由错误捕获(不使用则不会捕获异常错误)

module.exports = ct(async (req, res) => {
  let { start_createdAt, end_createdAt, logContent, limit, offset, sort } = req.body

  limit = limit || 20  // 限制读取的数据最大量
  offset = offset || 0  // 设置从第几条数据开始读取
  sort = sort ? ((_.keys(sort).length > 0) ? sort : { createdAt: 'DESC' }) : { createdAt: 'DESC' } // 设置默认排序条件

  // 查询条件
  const where = {}
  // 按账号创建时间范围匹配
  if (start_createdAt && end_createdAt) {
    where.createdAt = {
      $gte: moment(start_createdAt).format("YYYY-MM-DD 00:00:00"),
      $lte: moment(end_createdAt).format("YYYY-MM-DD 23:59:59")
    }
  }
  // 模糊查询logContent
  if (logContent) {
    where.logContent = {
      $regexp: logContent
    }
  }

  // 排序条件
  const order = []
  for (let key in sort) {
    order.push([`${key}`, `${sort[key]}`])
  }

  const { count, rows } = await models.ServiceLog.findAndCount({
    where: where,
    order: order,
    offset: offset,
    limit: limit,
    attributes: ['id', 'logType', 'logContent', 'createdAt']
  })
  rows.map(el => {
    return el.get({ plain: true })
  })

  return res.json(
    errcode.SUCCESS({
      count: count,
      rows: rows
    })
  );
});